package com.farmer.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.Header;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.pojo.*;
import com.farmer.service.AdminService;
import com.farmer.service.MenuService;
import com.farmer.service.RoleService;
import com.farmer.utils.JwtHelper;
import com.farmer.utils.Result;
import com.farmer.utils.TreeUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system")
public class SystemController {

    public static final String ADMIN_NAME = "超级管理员";

    @Resource
    private RoleService roleService;

    @Resource
    private MenuService menuService;

    @Resource
    private AdminService adminService;

    @GetMapping("/role/list")
    public Result<IPage<Role>> getRoleList(Role role) {
        LambdaQueryWrapper<Role> qw = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(role.getRname())) {
            qw.like(Role::getRname, role.getRname());
        }
        // 创建分页构造对象
        Page<Role> page = new Page<>(role.getPageNum(), role.getPageSize());
        // 执行分页查询
        IPage<Role> result = roleService.getBaseMapper().selectPage(page, qw);
        // 封装到统一响应体Result中
        return Result.ok(result);
    }

    /*
    * 新增角色，保存新增的角色信息*/
    @PostMapping("/role")
    public Result<String> saveRole(@RequestBody Role role) {
        String rname = role.getRname();
        if (StrUtil.isBlank(rname)) {
            return Result.fault("角色名称不能为空");
        }

        if (ADMIN_NAME.equals(rname)) {
            return Result.fault("角色名称不能为" + ADMIN_NAME);
        }

        LambdaQueryWrapper<Role> qw = Wrappers.lambdaQuery();
        qw.eq(Role::getRname, rname);
        Role r = roleService.getBaseMapper().selectOne(qw);
        if (r != null) {
            return Result.fault("角色名称已存在");
        }
        // 执行分页查询
        roleService.getBaseMapper().insert(role);
        // 封装到统一响应体Result中
        return Result.ok("新增角色成功");
    }

/*修改角色，根据角色ID修改角色信息*/
    @PutMapping("/role")
    public Result<String> updateRole(@RequestBody Role role) {
        if (role.getRid() == null) {
            throw new RuntimeException("角色ID不能为空");
        }
        roleService.getBaseMapper().updateById(role);
        // 封装到统一响应体Result中
        return Result.ok("修改角色成功");
    }

/*根据角色id删除角色信息，并删除角色关联的菜单和用户信息*/
    @DeleteMapping("/role/{roleIds}")
    public Result<String> updateRole(@PathVariable String roleIds) {
        if (StrUtil.isBlank(roleIds)) {
            throw new RuntimeException("角色ID不能为空");
        }
        List<String> ids = StrUtil.split(roleIds, StrUtil.COMMA);
        for (String id : ids) {
            roleService.getBaseMapper().deleteById(Integer.valueOf(id));
            roleService.deleteRoleMenusAndAdmins(Integer.valueOf(id));
        }
        // 封装到统一响应体Result中
        return Result.ok("删除角色成功");
    }

    /*
    * 根据角色ID查询角色信息*/
    @GetMapping("/role/{roleId}")
    public Result<Role> queryByRoleId(@PathVariable Integer roleId) {
        // 执行分页查询
        LambdaQueryWrapper<Role> lq = Wrappers.lambdaQuery();
        Role role = roleService.getBaseMapper().selectOne(lq.eq(Role::getRid, roleId));
        // 封装到统一响应体Result中
        return Result.ok(role);
    }

    //根据角色ID查询菜单列表
    @GetMapping("/role/menus/{roleId}")
    public Result<List<Menu>> queryMenusByRoleId(@PathVariable Integer roleId) {
        return Result.ok(roleService.selectMenusByRoleId(roleId));
    }

    //查询与特定角色ID关联的管理员（Admin）列表
    @GetMapping("/role/user/{roleId}")
    public Result<List<Admin>> queryUserByRoleId(@PathVariable Integer roleId) {
        return Result.ok(roleService.selectAdminByRoleId(roleId));
    }

//    提供菜单（Menu）数据的树形结构选择列表
    @GetMapping("/menu/treeselect")
    public Result<List<Menu>> getMenuList(Menu menu) {
        List<Menu> menus = menuService.getBaseMapper().selectList(Wrappers.emptyWrapper());
        return Result.ok(TreeUtils.buildTree(menus));
    }

//   获取所有菜单列表
    @GetMapping("/menu/list")
    public Result<List<Menu>> getAllMenu(Menu menu) {
        LambdaQueryWrapper<Menu> lq = Wrappers.lambdaQuery();
        String mname = menu.getMname();
        if (StrUtil.isNotBlank(mname)) {
            lq.like(Menu::getMname, mname);
        }
        List<Menu> menus = menuService.getBaseMapper().selectList(lq.ne(Menu::getParentid, 0));
        return Result.ok(menus);
    }
//
    @PutMapping("/menu")
    public Result<String> updateMenu(@RequestBody Menu menu) {
        menuService.getBaseMapper().updateById(menu);
        return Result.ok("修改菜单成功");
    }

    //菜单的ID来获取菜单的详细信息
    @GetMapping("/menu/{menuId}")
    public Result<Menu> getMenuById(@PathVariable("menuId") Integer menuId) {
        LambdaQueryWrapper<Menu> lq = Wrappers.lambdaQuery();
        Menu menus = menuService.getBaseMapper().selectOne(lq.eq(Menu::getMid, menuId));
        return Result.ok(menus);
    }
//以删除指定ID的菜单项
    @DeleteMapping("/menu/{menuId}")
    public Result<String> deleteMenu(@PathVariable("menuId") Integer menuId) {
        menuService.getBaseMapper().deleteById(menuId);
        menuService.deleteMenuRoles(menuId);
        return Result.ok("删除菜单成功");
    }

//分配用户那里显示的全部管理员
    @GetMapping("/user/list")
    public Result<List<Admin>> getAllUser() {
        LambdaQueryWrapper<Admin> lq = Wrappers.lambdaQuery();
        List<Admin> admins = adminService.getBaseMapper().selectList(lq.ne(Admin::getName, "超级管理员"));
        return Result.ok(admins);
    }

    //分配菜单
    @PutMapping("/role/menuallocation")
    public Result<String> menuAllocation(@RequestBody MenuAllocation menuAllocation) {
        menuService.menuAllocation(menuAllocation);
        return Result.ok("修改菜单数据权限成功");
    }

    ///system/role/userallocation
    /*
    @PutMapping("/role/userallocation")
    public Result<String> userAllocation(@RequestBody UserAllocation userAllocation) {
        adminService.userAllocation(userAllocation);
        return Result.ok("修改分配用户成功");
    }
    */
//    分配用户
    @PutMapping("/role/userallocation")
    public Result userAllocation(@RequestBody UserAllocation userAllocation){
        Result result = adminService.userAllocation(userAllocation);
        return result;
    }

/*
* 获取当前用户的菜单权限，并返回一个菜单树结构*/
    @GetMapping("/role/association/menu")
    public Result<List<Menu>> roleAssociationMenu(HttpServletRequest request) {
//        从一个请求中提取JWT（JSON Web Token）并从中获取用户ID
        String authorization = request.getHeader(Header.AUTHORIZATION.getValue());
        String token = StrUtil.subAfter(authorization, "Bearer ", false);
        Long userId = SpringUtil.getBean(JwtHelper.class).getUserId(token);
        List<Menu> allMenus = menuService.getBaseMapper().selectList(Wrappers.emptyWrapper());
        List<Menu> menuTree = TreeUtils.buildTree(allMenus);
        List<Menu> userMenuList = menuService.getUserMenus(userId);
//        过滤菜单树
//        创建了一个Set集合，用于存储不重复的整数
        Set<Integer> ids = userMenuList.stream().map(Menu::getMid).collect(Collectors.toSet());
        TreeUtils.foreachPredicate(menuTree, (menu, isLeaf) -> !isLeaf || ids.contains(menu.getMid()));
        return Result.ok(menuTree);
    }
}
